//
//  CHSingleButtonView.swift
//  CHSimpleUI
//
//  Created by cyptt on 2023/4/20.
//

import UIKit

public class CHSingleChioseScroll: UIView {
    
    private var selfW: CGFloat = 0
    private var selfH: CGFloat = 0
    private var isShowView: Bool = false
    
    private var titleLocal: CH_SINGLE_BUTTON_TITLE_LOCAL0 = .center
    private var titleArr: [String] = []
    private var defaultColor: UIColor = CHSIGLE_CHIOSE_CONST.defaultColor
    private var selectedColor: UIColor = CHSIGLE_CHIOSE_CONST.selectedColor
    private var defFont: UIFont = CHSIGLE_CHIOSE_CONST.defFont
    private var selFont: UIFont = CHSIGLE_CHIOSE_CONST.selFont
    
    private var defBgColor: UIColor = CHSIGLE_CHIOSE_CONST.defBgColor
    private var selBgColor: UIColor = CHSIGLE_CHIOSE_CONST.selectBgColor
    
    private var lineColor: UIColor = CHSIGLE_CHIOSE_CONST.lineColor
    private var currentBtn: UIButton?
    private var clickItemCallBack: ((_ index: Int, _ title: String?) -> ())?
    
    private let SigleChioseTAG: Int = 100000
    
    private var lineWith: CGFloat = CHSIGLE_CHIOSE_CONST.lineW
    private var lineH: CGFloat = CHSIGLE_CHIOSE_CONST.lineH
    
    private var itemW: CGFloat?
    private var defIndex: Int = 0
    
    private var buttonArr: [UIButton] = []
    private var lineArr: [UILabel] = []
    
    // 新增属性 - 滑动支持
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    private var isScrollingProgrammatically = false
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        initViews()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        initViews()
    }
    
    /*
     @param titleArr 请title个数数组
     @param local 位置
     @param defaultColor 默认颜色
     @param selectedColor 选中颜色
     @param defFont 正常字体
     @param selFont 选中字体
     @param lineColor 线条颜色
     @param lineW 线条宽度 不设置和字同宽
     @param lineH 线条高度 默认2
     @param itemW 每个item宽度，不设置默认等分
     @param defIndex 默认选择第几个
     @param defBgColor 默认背景颜色
     @param selBgColor 选中背景颜色
     */
    public func setTitleArr(titleArr: [String], local: CH_SINGLE_BUTTON_TITLE_LOCAL0 = .center, defaultColor: UIColor = CHSIGLE_CHIOSE_CONST.defaultColor, selectedColor: UIColor = CHSIGLE_CHIOSE_CONST.selectedColor, defFont: UIFont = CHSIGLE_CHIOSE_CONST.defFont, selFont: UIFont = CHSIGLE_CHIOSE_CONST.selFont, lineColor: UIColor = CHSIGLE_CHIOSE_CONST.lineColor, lineW: CGFloat = CHSIGLE_CHIOSE_CONST.lineW, lineH: CGFloat = CHSIGLE_CHIOSE_CONST.lineH, itemW: CGFloat? = nil, defIndex: Int = 0, defBgColor: UIColor = CHSIGLE_CHIOSE_CONST.defBgColor, selBgColor: UIColor = CHSIGLE_CHIOSE_CONST.selectBgColor) {
        self.isShowView = true
        self.titleArr = titleArr
        self.defaultColor = defaultColor
        self.selectedColor = selectedColor
        self.defFont = defFont
        self.selFont = selFont
        self.lineColor = lineColor
        self.lineWith = lineW
        self.lineH = lineH
        self.titleLocal = local
        self.itemW = itemW
        self.defIndex = defIndex
        self.defBgColor = defBgColor
        self.selBgColor = selBgColor
    }
    
    private func initViews() {
        self.isShowView = false
        selfW = self.frame.size.width
        selfH = self.frame.size.height
        
        // 初始化滚动视图
        setupScrollView()
    }
    
    private func setupScrollView() {
        // 创建滚动视图
        scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.delegate = self
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(scrollView)
        
        // 添加约束
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
        
        // 内容视图
        contentView = UIView()
        contentView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(contentView)
        
        // 内容视图约束
        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
        ])
    }
    
    public func btnClickIndexBlockFun(clouse: @escaping(_ index: Int, _ title: String?) -> Void) {
        self.clickItemCallBack = clouse
    }
    
    public func freshItem(index: Int, title: String) {
        guard index < buttonArr.count else { return }
        
        let btn: UIButton = self.buttonArr[index]
        btn.setTitle(title, for: .normal)
        
        self.freshDataArr(index: index, title: title)
        self.refreshLineView()
    }
    
    public func selectIndex(index: Int) {
        guard index < buttonArr.count else { return }
        
        let btn: UIButton = self.buttonArr[index]
        self.btnClick(btn: btn)
        
        // 确保选中的按钮在可视区域内
        scrollToVisible(button: btn)
    }
    
    /*
     刷新数组
     */
    private func freshDataArr(index: Int, title: String) {
        self.titleArr[index] = title
    }
    
    private func refreshLineView() {
        for i in 0..<self.lineArr.count {
            let lineView: UILabel = self.lineArr[i]
            let btn = self.buttonArr[i]
            
            var lineW: CGFloat = 0
            if self.lineWith != 0 {
                lineW = self.lineWith
            } else {
                lineW = self.getWidthWithString(titleString: self.titleArr[i], font: self.defFont)
            }
            
            let line_CenterY: CGFloat = selfH - (self.lineH / 2)
            let line_CenterX = btn.center.x
            
            lineView.frame = CGRect(x: 0, y: 0, width: lineW, height: self.lineH)
            lineView.center = CGPoint(x: line_CenterX, y: line_CenterY)
        }
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        selfW = self.frame.size.width
        selfH = self.frame.size.height
        
        // 保证只加载一次
        if self.isShowView {
            showSelectView()
        }
        
        self.isShowView = false
    }
    
    func showSelectView() {
        // 移除旧的视图
        buttonArr.forEach { $0.removeFromSuperview() }
        lineArr.forEach { $0.removeFromSuperview() }
        buttonArr.removeAll()
        lineArr.removeAll()
        
        // 计算内容宽度
        var contentWidth: CGFloat = 0
        let buttonHeight: CGFloat = selfH - 10
        
        for i in 0..<self.titleArr.count {
            // 计算按钮宽度
            var buttonWidth: CGFloat
            if let customWidth = self.itemW {
                buttonWidth = customWidth
            } else {
                // 如果没有设置固定宽度，则根据文本计算宽度
                let textWidth = self.getWidthWithString(titleString: self.titleArr[i], font: self.defFont)
                buttonWidth = textWidth + 20 // 添加一些内边距
            }
            
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: contentWidth, y: 0, width: buttonWidth, height: buttonHeight)
            contentView.addSubview(btn)
            
            btn.setTitle(self.titleArr[i], for: .normal)
            btn.setTitleColor(self.defaultColor, for: .normal)
            btn.setTitleColor(self.selectedColor, for: .selected)
            btn.layer.cornerRadius = (selfH - 10)/2
            btn.layer.masksToBounds = true
            
            // 设置按钮背景颜色
            btn.backgroundColor = self.defBgColor
            if i == self.defIndex {
                btn.backgroundColor = self.selBgColor
            }
            
            btn.titleLabel?.font = self.defFont
            
            if self.titleLocal == .left {
                btn.contentHorizontalAlignment = .left
                btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
            } else if self.titleLocal == .center {
                btn.contentHorizontalAlignment = .center
            } else if self.titleLocal == .right {
                btn.contentHorizontalAlignment = .right
                btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
            }
            
            if i == self.defIndex {
                btn.isSelected = true
                self.currentBtn = btn
                self.currentBtn?.titleLabel?.font = self.selFont
            }
            
            btn.tag = SigleChioseTAG + i
            btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
            
            self.buttonArr.append(btn)
            
            // 创建指示线
            let lineView = UILabel()
            lineView.backgroundColor = self.lineColor
            lineView.layer.cornerRadius = self.lineH / 2
            lineView.layer.masksToBounds = true
            lineView.isHidden = !btn.isSelected
            
            contentView.addSubview(lineView)
            self.lineArr.append(lineView)
            
            contentWidth += buttonWidth
        }
        
        // 设置内容视图的宽度
        contentView.widthAnchor.constraint(equalToConstant: contentWidth).isActive = true
        
        // 刷新指示线位置
        self.refreshLineView()
        
        // 设置初始选中状态
        if defIndex < buttonArr.count {
            let initialBtn = buttonArr[defIndex]
            scrollToVisible(button: initialBtn, animated: false)
        }
    }
    
    // 确保按钮在可视区域内
    private func scrollToVisible(button: UIButton, animated: Bool = true) {
        let buttonFrame = button.frame
        let visibleRect = CGRect(
            x: scrollView.contentOffset.x,
            y: scrollView.contentOffset.y,
            width: scrollView.bounds.width,
            height: scrollView.bounds.height
        )
        
        // 如果按钮不在可视区域内，滚动到中心
        if !visibleRect.contains(buttonFrame) {
            let targetX = buttonFrame.midX - scrollView.bounds.width / 2
            let maxOffsetX = max(0, scrollView.contentSize.width - scrollView.bounds.width)
            let minOffsetX: CGFloat = 0
            
            let adjustedOffsetX = max(min(targetX, maxOffsetX), minOffsetX)
            
            if animated {
                isScrollingProgrammatically = true
                UIView.animate(withDuration: 0.3, animations: {
                    self.scrollView.contentOffset.x = adjustedOffsetX
                }) { _ in
                    self.isScrollingProgrammatically = false
                }
            } else {
                self.scrollView.contentOffset.x = adjustedOffsetX
            }
        }
    }
}

// BTN --click
extension CHSingleChioseScroll {
    @objc func btnClick(btn: UIButton) {
        // 更新之前选中的按钮状态
        self.currentBtn?.isSelected = false
        self.currentBtn?.titleLabel?.font = self.defFont
        self.currentBtn?.backgroundColor = self.defBgColor
        
        // 更新当前选中的按钮状态
        btn.isSelected = true
        btn.titleLabel?.font = self.selFont
        btn.backgroundColor = self.selBgColor
        self.currentBtn = btn
        
        let index = btn.tag - SigleChioseTAG
        
        // 更新指示线
        for i in 0..<self.lineArr.count {
            let lineView: UILabel = self.lineArr[i]
            lineView.isHidden = i != index
        }
        
        // 滚动到选中按钮
        scrollToVisible(button: btn)
        
        if let callback = self.clickItemCallBack {
            callback(index, btn.currentTitle)
        }
    }
}

// UIScrollViewDelegate 实现
extension CHSingleChioseScroll: UIScrollViewDelegate {
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 如果不是程序触发的滚动，可以在这里处理用户滑动时的逻辑
        if !isScrollingProgrammatically {
            // 可以添加滑动时的额外效果
        }
    }
}

extension CHSingleChioseScroll {
    func getWidthWithString(titleString: String, font: UIFont) -> CGFloat {
        let attrs = [NSAttributedString.Key.font: font]
        let width: CGFloat = titleString.boundingRect(
            with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
            options: [.usesLineFragmentOrigin],
            attributes: attrs,
            context: nil
        ).size.width
        return width
    }
}

